/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.blacklist;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class BlacklistFileHandler {

    private File blacklistFile;
    public Set<String> currentBlacklist;
    private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    public BlacklistFileHandler(File blacklistFile) {
        this.blacklistFile = blacklistFile;
        loadBlacklistFromFile();
    }

    private synchronized void loadBlacklistFromFile() {
        try {
            logger.debug("Loading blacklist from file: {}", blacklistFile.getPath());
            List<String> blacklistFileLines = FileUtils.readLines(blacklistFile);
            currentBlacklist = Collections.synchronizedSet(new TreeSet<String>());
            for (String line : blacklistFileLines) {
                try {
                    String[] tokens = line.split(" ");
                    currentBlacklist.add(tokens[3]);
                } catch (Exception ex) {
                    logger.error("Cannot parse line [{}]: ", line, ex);
                }
            }
            logger.debug("Blacklist loaded");
        } catch (IOException ex) {
            logger.error("Cannot open file {}: ", blacklistFile, ex);
        } catch (Exception ex) {
            logger.error("", ex);
        }
    }

    public synchronized void updateBlacklistToFile() throws IOException {
        File backupFile = new File(blacklistFile.getAbsolutePath() + "_bak");
        FileUtils.copyFile(blacklistFile, backupFile);
        int ruleIndex = 1;
        List<String> lines = new ArrayList<String>(currentBlacklist.size());
        for (String msisdn : currentBlacklist) {
            String lineToAdd = "-n B" + (ruleIndex++) + " -s " + msisdn + " -j DROP";
            lines.add(lineToAdd);
        }
        FileUtils.writeLines(blacklistFile, lines);
    }

    public synchronized void restoreBackupFile() throws IOException {
        FileUtils.deleteQuietly(blacklistFile);
        File backupFile = new File(blacklistFile.getAbsolutePath() + "_bak");
        FileUtils.copyFile(backupFile, blacklistFile);
        FileUtils.deleteQuietly(backupFile);
        loadBlacklistFromFile();
    }
}
